﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using Flagwind.Resources;
using Flagwind.Services;
using Flagwind.Services;
using Flagwind.Resources;

namespace Flagwind.Plugins.Commands
{
	[DisplayName("${Text.FindCommand}")]
	[Description("${Text.FindCommand.Description}")]
	[CommandOption("obtain", Type = typeof(ObtainMode), DefaultValue = ObtainMode.Never, Description = "${Text.FindCommand.Options.ObtainMode}")]
	[CommandOption("maxDepth", Type = typeof(int), DefaultValue = 3, Description = "${Text.FindCommand.Options.MaxDepth}")]
	public class FindCommand : CommandBase<CommandContext>
	{
		#region 成员字段

		private PluginContext _pluginContext;

		#endregion

		#region 构造方法

		public FindCommand(PluginContext pluginContext) : this("Find", pluginContext)
		{
		}

		public FindCommand(string name, PluginContext pluginContext) : base(name)
		{
			if(pluginContext == null)
			{
				throw new ArgumentNullException("pluginContext");
			}

			_pluginContext = pluginContext;
		}

		#endregion

		#region 重写方法

		protected override object OnExecute(CommandContext context)
		{
			if(context.Expression.Arguments.Length == 0)
			{
				throw new CommandException(ResourceUtility.GetString("Text.Message.MissingCommandArguments"));
			}

			var result = new PluginTreeNode[context.Expression.Arguments.Length];

			for(int i = 0; i < context.Expression.Arguments.Length; i++)
			{
				result[i] = _pluginContext.PluginTree.Find(context.Expression.Arguments[i]);

				if(result[i] == null)
				{
					context.Output.WriteLine(CommandOutletColor.DarkRed, ResourceUtility.GetString("Text.Message.PluginNodeNotFound", context.Expression.Arguments[i]));
				}

				Utility.PrintPluginNode(context.Output, result[i], context.Expression.Options.GetValue<ObtainMode>("obtain"), context.Expression.Options.GetValue<int>("maxDepth"));
			}

			if(result.Length == 1)
			{
				return result[0];
			}

			return result;
		}

		#endregion
	}
}